<template>
  <div>
    <!-- 面包屑导航 -->
    <el-header>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>

    <!-- 主体部分 -->
    <el-card>
      <!-- 提示部分 -->
      <el-alert title="添加商品信息" type="info"
                center show-icon :closable="false">
      </el-alert>

      <!-- 步骤条 -->
      <el-steps :active="+active.index" finish-status="success" align-center>
        <el-step v-for="item in active.data" :title="item"></el-step>
<!--        <el-step title="完成"></el-step>-->
      </el-steps>

      <!-- 总数据表单 -->
      <el-form ref="addGoodForm"
               :model="addGoodForm.data"
               :rules="addGoodForm.rules">
        <!-- tabs标签页 -->
        <el-tabs tab-position="left" :before-leave="beforeLeave">
          <!-- 基本信息页 -->
          <el-tab-pane :label="active.data[0]" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addGoodForm.data.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="addGoodForm.data.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="cid">
              <el-cascader
                      clearable
                      :options="categoriesData"
                      v-model="addGoodForm.data.cid"
                      :props="addGoodForm.props">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数页 -->
          <el-tab-pane :label="active.data[1]" name="1">
            <div>
              <p>动态参数</p>
              <!-- 动态参数多选组 -->
              <el-checkbox-group v-model="selectedParams"
                                 v-if="params.dynamic.length">
                <el-checkbox v-for="item in params.dynamic"
                             :label="item.name" @change="changeCheckbox"></el-checkbox>
              </el-checkbox-group>
              <el-table v-else border></el-table>
              <p>静态属性</p>
              <!-- 静态参数多选组 -->
              <el-checkbox-group v-model="selectedParams"
                                 v-if="params.static.length">
                <el-checkbox v-for="item in params.static"
                             :label="item.name" @change="changeCheckbox"></el-checkbox>
              </el-checkbox-group>
              <el-table v-else border></el-table>
              <p>参数填写</p>
              <!-- 参数填写输入框 -->
              <div v-if="selectedParams.length">
                <el-form-item v-for="item in sortedSelectedParams"
                              :prop="`params.${item.name}`"
                              :rules="addGoodForm.rules.params"
                              :label="item.name" :key="item.id">
                  <el-input v-model="addGoodForm.data.params[item.name]"></el-input>
                </el-form-item>
              </div>
              <el-table v-else border></el-table>
            </div>
          </el-tab-pane>
          <!-- 商品图片页 -->
          <el-tab-pane :label="active.data[2]" name="2">
            <!-- 上传图片组件 -->
            <el-upload action="http://127.0.0.1:8000/upload/img/"
                       ref="upload"
                       :with-credentials="true"
                       :auto-upload="false"
                       list-type="picture"
                       :on-success="onSuccess"
                       :on-change="onChange"
                       :on-remove="onRemove">
              <!-- 添加图片按钮 -->
              <el-button slot="trigger" size="small" type="primary">添加图片</el-button>
              <!-- 上传服务器按钮 -->
              <el-button style="margin-left: 10px;"
                         size="small" type="success"
                         @click="$refs.upload.submit()">
                上传到服务器
              </el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容页 -->
          <el-tab-pane :label="active.data[3]" name="3">
            <quill-editor v-model="addGoodForm.data.direction"></quill-editor>
            <el-row class="button-box">
              <el-button type="primary" @click="addGoodFormSubmit">添加商品</el-button>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 缩略图弹出框 -->
      <el-dialog
              title="图片预览" width="50%"
              :visible.sync="imgVisible">
        <img class="show-img" :src="imgUrl" alt="缩略图"/>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 引入富文本编辑器
import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'Add',
  data() {
    return {
      // 商品分类原始数据
      categoriesSourceData: [],
      // 选中参数列表
      selectedParams: [],
      // 存放图片列表
      imgList: [],
      // 控制图片预览是否显示
      imgVisible: false,
      // 图片预览连接
      imgUrl: '',
      // 图片上传请求头
      imgHeaders: {},
      // 步骤条和tabs的数据和选中项
      active: {
        // 选中项index
        index: '0',
        data: ['基本信息', '商品参数', '商品图片', '商品内容']
      },
      // 该分类下的所有参数，static和dynamic
      params: {
        dynamic: [],
        static: []
      },
      // 添加商品表单
      addGoodForm: {
        data: {
          name: '',
          price: '',
          // 选中参数的键值
          params: {},
          // 商品分类id
          cid: 0,
          // 商品描述
          direction: '',
          // 图片列表
          images: []
        },
        rules: {
          name: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],
          price: [{ required: true, message: '商品价格不能为空', trigger: 'blur' }],
          params: [{ required: true, message: '参数值不能为空', trigger: 'blur' }]
        },
        // 级联选择框配置参数
        props: {
          value: 'id',
          label: 'name',
          children: 'children',
          emitPath: false,
          expandTrigger: 'hover'
        }
      }
    }
  },
  components: { quillEditor },
  computed: {
    // 商品分类数据
    categoriesData() {
      // 列表复制
      let newData = JSON.parse(JSON.stringify(this.categoriesSourceData))
      for (let item of newData)
        for (let item1 of item.children)
          for (let item2 of item1.children)
            item2.children = undefined
      return newData
    },
    // 排序后的选中标签
    sortedSelectedParams() {
      let list = []
      this.params.dynamic.forEach(item => {
        if (this.selectedParams.indexOf(item.name) !== -1)
          list.push(item)
      })
      this.params.static.forEach(item => {
        if (this.selectedParams.indexOf(item.name) !== -1)
          list.push(item)
      })
      return list
    }
  },
  methods: {
    // tabs组件离开标签页时触发
    beforeLeave(index, oldIndex) {
      // 进入标签条件
      if (!this.addGoodForm.data.cid && oldIndex) {
        this.$message.error('请先选择商品分类')
        return false
      }
      // 获取商品参数
      else if (index === '1')
        this.getParamsData()
      this.active.index = index
      return true
    },
    // 获取商品分类数据
    async getCategoriesData() {
      let { data: res } = await this.$ajax.get('categories/')
      if (res.status === 'success') {
        this.categoriesSourceData = res.data
        this.$message.success('获取商品分类参数成功')
      } else
        this.$message.error('获取商品分类参数失败')
    },
    // 获取该分类全部参数数据
    async getParamsData() {
      let cid = this.addGoodForm.data.cid
      let { data: res } = await this.$ajax.get(`params/all/${cid}/`)
      if (res.status === 'success') {
        this.params = res.data
        this.$message.success('获取参数成功')
      } else
        this.$message.error('获取参数失败')
    },
    // 多选框改变时调用
    changeCheckbox(type, event) {
      // 在多选框取消选中时删除属性
      if (!type)
        delete this.addGoodForm.data.params[event.target.defaultValue]
    },
    // 图片 添加、上传成功、上传失败、删除(设置on-remove=onChange)时调用
    onChange(file, fileList) {
      // 获取图片标签
      this.imgList = fileList
      // 为图片添加点击事件
      //  element-ui没提供相关功能  自己实现
      this.$nextTick(() => {
        let that = this
        // 强制延迟，否则获取到的children是删除之前的
        setTimeout(() => {
          // 为控件添加点击事件
          let children = document.getElementsByClassName('el-upload-list__item')
          for (let i = 0; i < children.length; i++) {
            let close = children[i].getElementsByClassName('el-icon-close')[0]
            close.onclick = e => {
              e.stopPropagation()
            }
            children[i].onclick = (function(i) {
              return function() {
                that.showImg(i)
              }
            })(i)
          }
        }, 500)
      })
    },
    onRemove(file, fileList) {
      // 获取上传后文件的列表
      let imgList = this.addGoodForm.data.images
      // 如果上传后文件列表中有要删除的文件，则移除
      // 若文件名相同，只移除第一个
      for (let i in imgList) {
        if (imgList[+i].name === file.name) {
          imgList.splice(+i, 1)
          break
        }
      }
      // 删除时也需要调用onChange
      this.onChange(file, fileList)
    },
    // 文件上传成功时操作
    onSuccess(res) {
      if (res.status === 'success') {
        this.addGoodForm.data.images.push(res.data)
        this.$message.success('图片上传成功')
        return
      }
      this.$message.error('图片上传失败')
    },
    // 展示缩略图
    showImg(index) {
      if (this.imgList[index]) {
        this.imgVisible = true
        this.imgUrl = this.imgList[index].url
      }
    },
    // 提交添加商品请求
    addGoodFormSubmit() {
      this.$refs.addGoodForm.validate(async valid => {
        if (!valid) return this.$message.error('请填写全部必填字段')
        let { data: res } = await this.$ajax.post('goods/add/', this.addGoodForm.data)
        if (res.status === 'OK') {
          this.$message.success('添加商品成功')
          await this.$router.push('/goods')
        } else
          this.$message.error('添加商品失败')
      })
    }
  },
  created() {
    this.getCategoriesData()
  }
}
</script>

<style scoped>
.el-header {
  display: flex;
  align-items: center;
}

.el-alert /deep/ .el-alert__content {
  display: flex;
  align-items: center;
}

.el-steps {
  margin: 10px 15px;
}

.el-tabs {
  user-select: none;
}

.show-img {
  width: 100%;
}

/deep/ .ql-editor {
  min-height: 300px !important;
}

.button-box {
  display: flex;
  justify-content: flex-end;
}

.button-box .el-button {
  margin: 15px 15px 0 0;
}
</style>